/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package job.manager.client.security;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.event.ActionEvent;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import job.manager.db.ec.UsersEB;
import job.manager.db.ex.UserNotFoundException;
import job.manager.db.sb.UserRemote;
/**
 *
 * @author Administrator
 */

public class LoginMB {
    @EJB
    private UserRemote userBean;

    private String user;
    private String password;
    private String errorMsg;
    private UsersEB userObject;

    /** Creates a new instance of LoginMB */
    public LoginMB() {

    }

    @PostConstruct
    public void onInit() {
        this.user = "";
        this.password = "";
        this.errorMsg = "";
        this.userObject = null;
    }

    public String loginUser() {
        this.errorMsg = "";
        try {
            userObject = userBean.login(user, password);
            userObject.setPassword("");
        } catch (UserNotFoundException ex) {
            this.errorMsg = ex.getMessage();
            return "fail";
        }
        return "success";
    }

    public boolean loggedIn(){
        return (userObject != null);
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getPassword() //always return empty string due to security
    {
        return "";
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUser() {
        return user;
    }

    public UsersEB getUserEB()
    {
        return this.userObject;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public void login(ActionEvent e) throws java.io.IOException {
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
 	String context = req.getContextPath();
        FacesContext.getCurrentInstance().getExternalContext().redirect(req.getContextPath() +"/j_spring_security_check?j_username=" + user + "&j_password=" + password);
    }
}
